package com.zzh.tree;

import java.util.*;

public class No103_zigzagLevelOrder {
    public static void main(String[] args) {
        No103Solution solution = new No103Solution();
        List<List<Integer>> lists = solution.zigzagLevelOrder(TreeNode.initTree());
        for (List<Integer> list : lists){
            System.out.println(Arrays.toString(list.toArray()));
        }
    }
}
class No103Solution{

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root==null){
            return new ArrayList<>();
        }
        List<List<Integer>> list=new ArrayList<>();
        Queue<TreeNode> q=new LinkedList<>();
        Stack<TreeNode> s=new Stack<>();
        boolean flag=true;
        s.push(root);
        while (!s.isEmpty()){
            int sz=s.size();
            List<Integer> temp=new ArrayList<>();
            for (int i=0;i<sz;i++){
                TreeNode cur=s.pop();
                temp.add(cur.val);
                if (flag){
                    //从左开始
                    if (cur.left!=null){
                        q.offer(cur.left);
                    }
                    if (cur.right!=null){
                        q.offer(cur.right);
                    }
                }
                else{
                    //从右开始
                    if (cur.right!=null){
                        q.offer(cur.right);
                    }
                    if (cur.left!=null){
                        q.offer(cur.left);
                    }
                }

            }
            flag=!flag;
            while (!q.isEmpty()){
                s.push(q.poll());
            }
            list.add(temp);
        }
        return list;
    }
}
